package com.system.core.baidumap;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.stereotype.Component;

import com.system.core.baidumap.dto.BaiduMapConfig;

import lombok.AllArgsConstructor;

@Component
@AllArgsConstructor
public class BaiduMapComponent {

	private final BaiduMapConfig baiduMapConfig;

	/**
	 * 计算sn跟参数对出现顺序有关，get请求请使用LinkedHashMap保存<key,value>，该方法根据key的插入顺序排序；
	 * post请使用TreeMap保存<key,value>，该方法会自动将key按照字母a-z顺序排序。
	 * 
	 * @return
	 * @throws Exception
	 */
	public String getsn(Map<String, Object> paramsMap, String uri) throws Exception {
		paramsMap.put("ak", baiduMapConfig.getAk());
		String paramsStr = toQueryString(paramsMap);
		String wholeStr = new String(uri + paramsStr + baiduMapConfig.getSk());
		System.out.println("wholeStr:"+wholeStr);
		String tempStr = URLEncoder.encode(wholeStr, "UTF-8");
		return MD5(tempStr);
	}

	// 对Map内所有value作utf8编码，拼接返回结果
	public String toQueryString(Map<?, ?> data) throws UnsupportedEncodingException {
		StringBuffer queryString = new StringBuffer();
		for (Entry<?, ?> pair : data.entrySet()) {
			queryString.append(pair.getKey() + "=");
			queryString.append(URLEncoder.encode((String) pair.getValue(), "UTF-8") + "&");
		}
		if (queryString.length() > 0) {
			queryString.deleteCharAt(queryString.length() - 1);
		}
		return queryString.toString();
	}

	// 来自stackoverflow的MD5计算方法，调用了MessageDigest库函数，并把byte数组结果转换成16进制
	public String MD5(String md5) {
		try {
			java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
			byte[] array = md.digest(md5.getBytes());
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < array.length; ++i) {
				sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1, 3));
			}
			return sb.toString();
		} catch (java.security.NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return null;
	}
}
